package edu.wong.pro.serviceImpl;

import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.springframework.beans.FatalBeanException;

import edu.wong.pro.dao.IndividoualActivityDAO;
import edu.wong.pro.iservice.IIndiAct;
import edu.wong.pro.model.IndividoualActivity;

public class IndiActService implements IIndiAct{

	//发布个人活动
	@Override
	public boolean relIndiAct(String indiTheme, String indiContent,
			String indiDate, String indiAddition) {
		// TODO Auto-generated method stub
		HttpSession httpSession = ServletActionContext.getRequest().getSession();
		int memId = (Integer)httpSession.getAttribute("memberID");
		int indiID =new Random(new Date().getTime()).nextInt();
		IndividoualActivity activity = new IndividoualActivity(indiID,memId, indiTheme, indiContent, indiDate, indiAddition, null);
		IndividoualActivityDAO dao = new IndividoualActivityDAO();
		Session session = dao.getSession();
		Transaction transaction = session.beginTransaction();
		dao.save(activity);
		transaction.commit();
		session.close();
		return true;
	}

	//获取个人活动
	@Override
	public JSONArray getMyIndiAct() {
		// TODO Auto-generated method stub
		HttpSession httpSession = ServletActionContext.getRequest().getSession();
		int memId = (Integer)httpSession.getAttribute("memberID");
		IndividoualActivityDAO dao = new IndividoualActivityDAO();	
		List<IndividoualActivity> list = dao.findByProperty("memId", memId);
		if(list!=null){
			for (IndividoualActivity individoualActivity : list) {
				System.out.println("indiactivid:"+individoualActivity.getIndividualId());
			}
		
		}
		return JSONArray.fromObject(list);
	}
	//获取前10条最新个人活动
	@Override
	public JSONArray getTopIndiAct() {
		// TODO Auto-generated method stub
		Configuration cfg = new Configuration().configure();
		SessionFactory factory = cfg.buildSessionFactory();
		Session  session = factory.openSession(); 
		Query query = session.createQuery(" from IndividoualActivity order by individaulDate desc");
		query.setMaxResults(10);
		List<IndividoualActivity> list = query.list();
		session.close();
		factory.close();
		return JSONArray.fromObject(list);
	}

	//通过ID获取个人活动
	@Override
	public JSONObject getIndiActByID(String indiActId) {
		// TODO Auto-generated method stub
		int id = Integer.parseInt(indiActId);
		IndividoualActivityDAO dao = new IndividoualActivityDAO();
		return JSONObject.fromObject(dao.findById(id));
	}

}
